package com.rede.didiok.rank.service.impl;

import java.util.*;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rede.didiok.common.constant.conf.MessageConf;
import com.rede.didiok.common.constant.conf.RedisConf;
import com.rede.didiok.common.constant.conf.SQLConf;
import com.rede.didiok.common.constant.conf.SysConf;
import com.rede.didiok.common.constant.global.Constants;
import com.rede.didiok.common.dto.rank.MemberGradeDto;
import com.rede.didiok.common.enums.LevelEnum;
import com.rede.didiok.common.enums.StatusEnum;
import com.rede.didiok.common.utils.*;
import com.rede.didiok.rank.dao.MemberGradeDao;
import com.rede.didiok.rank.entity.MemberGradeEntity;
import com.rede.didiok.rank.entity.RankMemberEntity;
import com.rede.didiok.rank.service.MemberGradeService;
import com.rede.didiok.rank.service.RankMemberService;


@Service("memberGradeService")
public class MemberGradeServiceImpl extends ServiceImpl<MemberGradeDao, MemberGradeEntity> implements MemberGradeService {

    @Resource
    private RankMemberService rankMemberService;
    @Resource
    private RedisUtil redisUtil;


    /***************************** admin:start **************************/
    // region  didiok-admin

    @Override
    public IPage<MemberGradeEntity> getPageList(MemberGradeDto memberGradeDto) {
        QueryWrapper<MemberGradeEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(memberGradeDto.getKeyword()) && !StringUtils.isEmpty(memberGradeDto.getKeyword())) {
            queryWrapper.like(SQLConf.GRADE_NAME, memberGradeDto.getKeyword().trim());
        }

        Page<MemberGradeEntity> page = new Page<>();
        page.setCurrent(memberGradeDto.getCurrentPage());
        page.setSize(memberGradeDto.getPageSize());
        queryWrapper.eq(SQLConf.STATUS, StatusEnum.ENABLE);
        if (StringUtils.isNotEmpty(memberGradeDto.getOrderByAscColumn())) {
            // 将驼峰转换成下划线
            String column = StringUtils.underLine(new StringBuffer(memberGradeDto.getOrderByAscColumn())).toString();
            queryWrapper.orderByAsc(column);
        } else if (StringUtils.isNotEmpty(memberGradeDto.getOrderByDescColumn())) {
            // 将驼峰转换成下划线
            String column = StringUtils.underLine(new StringBuffer(memberGradeDto.getOrderByDescColumn())).toString();
            queryWrapper.orderByDesc(column);
        } else {
            queryWrapper.orderByDesc(SQLConf.SORT);
        }
        IPage<MemberGradeEntity> pageList = this.page(page, queryWrapper);
        return pageList;
    }

    @Override
    public String addMemberGrade(MemberGradeDto memberGradeDto) {
        QueryWrapper<MemberGradeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConf.NOTE, memberGradeDto.getNote());
        queryWrapper.eq(SQLConf.STATUS, StatusEnum.ENABLE);
        MemberGradeEntity tempMemberGrade = this.getOne(queryWrapper);
        if (tempMemberGrade != null) {
            return ResultUtil.errorWithMessage(MessageConf.ENTITY_EXIST);
        }
        MemberGradeEntity memberGradeEntity = new MemberGradeEntity();
        memberGradeEntity.setNote(memberGradeDto.getNote());
        memberGradeEntity.setStatus(StatusEnum.ENABLE);
        memberGradeEntity.setSort(memberGradeDto.getSort());
        memberGradeEntity.insert();
        // 删除Redis中的  MemberGrade
        deleteRedisMemberGradeList();
        return ResultUtil.successWithMessage(MessageConf.INSERT_SUCCESS);
    }

    @Override
    public String editMemberGrade(MemberGradeDto memberGradeDto) {
        MemberGradeEntity rank = this.getById(memberGradeDto.getUid());

        if (rank != null && !rank.getNote().equals(memberGradeDto.getNote())) {
            QueryWrapper<MemberGradeEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(SQLConf.NOTE, memberGradeDto.getNote());
            queryWrapper.eq(SQLConf.STATUS, StatusEnum.ENABLE);
            MemberGradeEntity tempMemberGrade = this.getOne(queryWrapper);
            if (tempMemberGrade != null) {
                return ResultUtil.errorWithMessage(MessageConf.ENTITY_EXIST);
            }
        }

        rank.setNote(memberGradeDto.getNote());
        rank.setStatus(StatusEnum.ENABLE);
        rank.setSort(memberGradeDto.getSort());
        rank.updateById();
        // 删除和标签相关的博客缓存
        this.deleteRedisByMemberGrade();
        // 删除Redis中的BLOG_TAG
        deleteRedisMemberGradeList();
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    @Override
    public String deleteBatchMemberGrade(List<MemberGradeDto> rankVOList) {
        if (rankVOList.size() <= 0) {
            return ResultUtil.errorWithMessage(MessageConf.PARAM_INCORRECT);
        }
        List<String> uids = new ArrayList<>();
        rankVOList.forEach(item -> {
            uids.add(item.getUid());
        });

        // 判断要删除的分类，是否有博客
        QueryWrapper<RankMemberEntity> blogQueryWrapper = new QueryWrapper<>();
        blogQueryWrapper.eq(SQLConf.STATUS, StatusEnum.ENABLE);
        blogQueryWrapper.in(SQLConf.MEMBER_UID, uids);
        Integer blogCount = rankMemberService.count(blogQueryWrapper);
        if (blogCount > 0) {
            return ResultUtil.errorWithMessage(MessageConf.MEMBER_UNDER_THIS_GRADE);
        }

        Collection<MemberGradeEntity> rankList = this.listByIds(uids);

        rankList.forEach(item -> {
            item.setStatus(StatusEnum.DISABLED);
        });

        Boolean save = this.updateBatchById(rankList);
        // 删除和标签相关的博客缓存
        this.deleteRedisByMemberGrade();
        // 删除Redis中的BLOG_TAG
        deleteRedisMemberGradeList();
        if (save) {
            return ResultUtil.successWithMessage(MessageConf.DELETE_SUCCESS);
        } else {
            return ResultUtil.errorWithMessage(MessageConf.DELETE_FAIL);
        }
    }

    // endregion
    /***************************** admin:end **************************/



    /***************************** web:start **************************/
    // region didiok-web

    @Override
    public List<MemberGradeEntity> getList() {
        QueryWrapper<MemberGradeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SysConf.STATUS, StatusEnum.ENABLE);
        queryWrapper.orderByDesc(SQLConf.SORT);
        List<MemberGradeEntity> rankList = this.list(queryWrapper);
        return rankList;
    }

    // endregion
    /***************************** web:end **************************/

    /**
     * 批量：根据等级id列表，获取等级信息
     *
     * @param gradeIds
     * @return
     */
    @Override
    public List<MemberGradeEntity> getGradesByIds(List<Long> gradeIds) {
        return baseMapper.selectList(new QueryWrapper<MemberGradeEntity>().in("grade_id",gradeIds));
    }

    @Override
    public MemberGradeEntity getTopOne() {
        QueryWrapper<MemberGradeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConf.STATUS, StatusEnum.ENABLE);
        queryWrapper.last(SysConf.LIMIT_ONE);
        queryWrapper.orderByDesc(SQLConf.SORT);
        MemberGradeEntity gradeEntity = this.getOne(queryWrapper);
        return gradeEntity;
    }

    /**
     * 删除Redis中的rank列表
     */
    private void deleteRedisMemberGradeList() {
        // 删除Redis中的rank列表
        Set<String> keys = redisUtil.keys(RedisConf.MEMBER_GRADE + Constants.SYMBOL_COLON + "*");
        redisUtil.delete(keys);
    }

    @Override
    public void deleteRedisByMemberGrade() {
        // 删除Redis中榜单下的榜单成员数量
        redisUtil.delete(RedisConf.DASHBOARD + Constants.SYMBOL_COLON + RedisConf.RANK_MEMBER_COUNT_BY_RANK);

        // 删除榜单相关缓存
        redisUtil.delete(RedisConf.NEW_RANK);
        redisUtil.delete(RedisConf.HOT_RANK);
        redisUtil.delete(RedisConf.RANK_LEVEL + Constants.SYMBOL_COLON + LevelEnum.FIRST);
        redisUtil.delete(RedisConf.RANK_LEVEL + Constants.SYMBOL_COLON + LevelEnum.SECOND);
        redisUtil.delete(RedisConf.RANK_LEVEL + Constants.SYMBOL_COLON + LevelEnum.THIRD);
        redisUtil.delete(RedisConf.RANK_LEVEL + Constants.SYMBOL_COLON + LevelEnum.FOURTH);

        // 榜单成员相关缓存
        rankMemberService.deleteRedisByRankMember();
    }

}